<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('名称设置') }}</span>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('查询脚本')" prop="sqlBaseId">
            <el-select v-model="form.sqlBaseId" :placeholder="$t('查询脚本')" @change="searchSqlSelect">
              <el-option
                v-for="item in optionsList"
                :key="item.code"
                :label="$t(item.name)"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('视图名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('视图名称')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('排序')" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('筛选范围') }}</span>
      </div>
      <div class="rangeForm">
        <ul class="rangeBody">
          <li v-for="(item,index) in form.searchDefaultGroup" :key="index + new Date().getTime()">
            <div v-if="item.searchDefaultConditionsList && item.searchDefaultConditionsList.length > 0" class="head">
              <div class="select">
                {{ $t('组内关系') }}：
                <el-select v-model="item.relation" :placeholder="$t('请选择')">
                  <el-option v-for="item in item.relationList" :key="item.value" :label="$t(item.label)" :value="item.value" />
                </el-select>
              </div>
              <el-button icon="el-icon-delete" type="text" @click="delFiltrate(index)" />
            </div>
            <div v-if="item.searchDefaultConditionsList && item.searchDefaultConditionsList.length > 0" class="content">
              <div class="rangeItem">
                <div v-for="(Default,ind) in item.searchDefaultConditionsList" :key="ind + new Date().getTime()">
                  <span class="rangeIndex">{{ ind + 1 }}</span>
                  <!-- 动态选择select -->
                  <el-select v-model="Default.fieldId" filterable :placeholder="$t('请选择')" clearable @change="detailsChange(index, ind, $event)">
                    <el-option v-for="field in dealdetailsList" :key="field.name" :label="$t(field.remark)" :value="field.name" />
                  </el-select>
                  <!-- 等于不等于--- -->
                  <el-select v-model="Default.conditions" filterable :placeholder="$t('请选择')" clearable>
                    <el-option v-for="conditions in Default.conditionsList" :key="conditions.dictValue" :label="$t(conditions.dictLabel)" :value="conditions.dictValue" />
                  </el-select>
                  <searchMain v-model="Default.fieldValue" :type="Default.type" :choose-list="Default.chooseList" />
                  <el-button icon="el-icon-plus" type="info" size="mini" circle class="smallC" @click="addRange(item,index)" />
                  <el-button icon="el-icon-minus" type="info" size="mini" class="smallC" :disabled="disabledButton" circle @click="delRange(item,index)" />
                </div>
              </div>
            </div>
          </li>

        </ul>
        <div class="addBtn">
          <el-button icon="el-icon-plus" type="text" @click="addFiltrate()">{{ $t('添加筛选条件') }}</el-button>
        </div>
      </div>
      <el-row>
        <el-col :span="24">
          <div class="area-header">
            <span class="area-header-title">{{ $t('颜色设置') }}</span>
          </div>
          <el-color-picker
            v-model="form.color"
            show-alpha
            :predefine="predefineColors"
          />
        </el-col>
        <el-col :span="24">
          <div class="area-header" style="margin-top:15px;">
            <span class="area-header-title">{{ $t('展示字段') }}</span>
            <el-button type="primary" size="mini" style="float:right" @click="refresh">{{ $t('刷新') }}</el-button>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="list-group-th">
            <div>{{ $t('展示') }}</div>
            <div>{{ $t('字段名称') }}</div>
            <div style="width:160px;text-align: center;">{{ $t('是否固定') }}</div>
            <div>{{ $t('宽度') }}</div>
          </div>
          <draggable
            v-model="form.searchDefaultShowList"
            v-loading="sLoading"
            class="list-group"
            tag="ul"
            v-bind="dragOptions"
            @start="isDragging = true"
            @end="isDragging = false"
          >
            <transition-group type="transition" name="flip-list">
              <li
                v-for="(element, index) in form.searchDefaultShowList"
                :key="index + new Date().getTime()"
                class="list-group-item"
              >
                <el-slider v-model="element.width" :max="500" />
                <i
                  :class="
                    element.fixed ? 'fa fa-anchor' : 'glyphicon glyphicon-pushpin'
                  "
                  aria-hidden="true"
                  @click="element.fixed = !element.fixed"
                />
                <div class="showList">
                  <div class="wid"><el-checkbox v-model="element.isShow" true-label="Y" false-label="N" /></div>
                  <div class="wid">{{ $t(element.fieldName) }}</div>
                  <div class="wid" style="width:160px;text-align: center;">
                    <el-switch
                      v-model="element.isFixed"
                      active-value="Y"
                      inactive-value="N"
                    />
                  </div>
                  <div class="wid"><el-input-number v-model="element.width" size="small" :min="0" :max="500" /></div>
                </div>
              </li>
            </transition-group>
          </draggable>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button @click="resizeForm">{{ $t("重置") }}</el-button>
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['system:searchview:edit']" type="primary" @click="submitForm">{{ $t("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
import { getByBaseId } from '@/api/system/search/searchSqlField'
import { allListSearchSqlBase } from '@/api/system/search/searchSqlBase'
import { getSearchDefaultView, saveSearchDefaultView } from '@/api/system/search/searchDefaultView'
import draggable from 'vuedraggable'
import searchMain from './searchMain.vue'
export default {
  name: 'SearchDefaultViewForm',
  components: { draggable, searchMain },
  data() {
    return {
      num: 0,
      sLoading: false,
      loading: false,
      optionsList: [], // 查询脚本
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      // 表单参数
      form: {
        color: '',
        name: '',
        sqlBaseId: '',
        sort: '',
        searchDefaultShowList: [],
        searchDefaultGroup: [{
          // 组关系
          relation: 'and',
          relationList: [{ value: 'and', label: this.$t('且') }, { value: 'or', label: this.$t('或') }],
          // ---
          searchDefaultConditionsList: [
            {
              fieldId: '', // id
              fieldName: '', // name
              conditions: '', // 条件
              detailsList: this.dealdetailsList,
              conditionsList: this.conditionsList,
              type: '',
              fieldValue: '', // value
              // 字典list
              chooseList: []
              }
          ]
        }]
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        sqlBaseId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      active: false,
      disabledButton: false,
      background: '',
      // list
      dealdetailsList: [],
      // 组内关系
      rList: [{ value: 'and', label: this.$t('且') }, { value: 'or', label: this.$t('或') }],
      // 等于不等于...
      conditionsList: [],
      fieldslist: [
        {
          detailsList: this.dealdetailsList,
          conditionsList: this.conditionsList,
          type: ''
        }
      ],
      dictList: [],
      sortable: null
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      }
    }
  },
  watch: {
    'form.sqlBaseId': {
      handler(val) {
        // 脚本
        allListSearchSqlBase().then(response => {
          response.data.forEach(item => {
            if (item.code === val) {
              // 字段
              getByBaseId(item.id).then(resp => {
                  this.dealdetailsList = resp.data
                  // this.form.searchDefaultShowList = [] // 展示字段列表
                  // resp.data.forEach(element => {
                  //   const row = {
                  //     fieldName: element.name,
                  //     fieldRemark: element.remark,
                  //     isShow: element.isShow,
                  //     width: element.width,
                  //     isFixed: element.isFixed
                  //   }
                  //   if (!(this.form.searchDefaultShowList instanceof Array)) {
                  //     this.$set(this.form, 'searchDefaultShowList', [])
                  //   }
                  //   this.form.searchDefaultShowList.push(row)
                  // })
                  // 查询条件
                  this.form.searchDefaultGroup && this.form.searchDefaultGroup.forEach(item => {
                    // 且或
                    this.$set(item, 'relationList', this.rList)
                    item.relationList && item.relationList.forEach(rel => {
                      if (item.relation === rel.value) {
                        this.$set(item, 'relation', rel.label)
                      }
                    })
                    // 选择字段、条件
                    item.searchDefaultConditionsList.forEach(ele => {
                      this.$set(ele, 'detailsList', resp.data)
                      this.$set(ele, 'conditionsList', this.conditionsList)

                      resp.data.forEach(res => {
                        if (res.name === ele.fieldId) {
                          this.$set(ele, 'fieldName', res.name)
                          this.$set(ele, 'type', res.type)

                          if (res.format) {
                            // 字典options
                            this.getDicts(res.format).then(dict => {
                              this.$set(ele, 'chooseList', dict.data)
                            })
                          }
                        }
                      })
                    })
                  })
              })
            }
          })
        })
      },
      immediate: true, // 默认立即触发一次
      deep: true // 监听这个对象中的每一个属性变化

    }

  },
  created() {
    this.getDicts('calculation_conditions').then(response => {
      this.conditionsList = response.data
    })

    allListSearchSqlBase().then(response => {
      this.optionsList = response.data
    })
  },
  mounted() {
  },
  methods: {
    // 查询脚本
    searchSqlSelect(val) {
      allListSearchSqlBase().then(response => {
        response.data.forEach(item => {
          if (item.code === val) {
            getByBaseId(item.id).then(resp => {
                this.dealdetailsList = resp.data
                this.form.searchDefaultGroup[0].searchDefaultConditionsList[0].detailsList = resp.data
                this.form.searchDefaultShowList = [] // 展示字段列表
                  resp.data.forEach(element => {
                    const row = {
                      fieldName: element.name,
                      fieldRemark: element.remark,
                      isShow: element.isShow,
                      width: element.width,
                      isFixed: element.isFixed
                    }
                    if (!(this.form.searchDefaultShowList instanceof Array)) {
                      this.$set(this.form, 'searchDefaultShowList', [])
                    }
                    this.form.searchDefaultShowList.push(row)
                  })
            })
          }
        })
      })
    },
    // 刷新
    refresh() {
     allListSearchSqlBase().then(response => {
        response.data.forEach(item => {
          if (item.code === this.form.sqlBaseId) {
            getByBaseId(item.id).then(resp => {
                this.dealdetailsList = resp.data
                // this.form.searchDefaultGroup[0].searchDefaultConditionsList[0].detailsList = resp.data
                this.form.searchDefaultShowList = [] // 展示字段列表
                  resp.data.forEach(element => {
                    const row = {
                      fieldName: element.name,
                      fieldRemark: element.remark,
                      isShow: element.isShow,
                      width: element.width,
                      isFixed: element.isFixed
                    }
                    if (!(this.form.searchDefaultShowList instanceof Array)) {
                      this.$set(this.form, 'searchDefaultShowList', [])
                    }
                    this.form.searchDefaultShowList.push(row)
                  })
            })
          }
        })
      })
    },
    // 添加筛选条件
    addFiltrate() {
      const row = {
        // 组号
        sort: 0,
        // 组关系
        relation: 'and',
        relationList: this.rList,
        searchDefaultConditionsList: [
            {
              detailsList: this.dealdetailsList,
              conditionsList: this.conditionsList,
              type: ''
            }
          ]
      }
      if (!(this.form.searchDefaultGroup instanceof Array)) {
        this.$set(this.form, 'searchDefaultGroup', [])
      }
      this.form.searchDefaultGroup.push(row)
    },
    // 重置表单
    resizeForm() {
      this.form = {
          name: '',
          color: '',
          sort: '',
          sqlBaseId: '',
          searchDefaultShowList: [],
          searchDefaultGroup: [
            {
              relation: 'and',
              relationList: this.rList,
              searchDefaultConditionsList: [
                {
                    fieldId: '', // id
                    fieldName: '', // name
                    conditions: '', // 条件
                    detailsList: this.dealdetailsList,
                    conditionsList: this.conditionsList,
                    type: '',
                    fieldValue: '', // value
                    // 字典list
                    chooseList: []
                  }
              ]
            }
          ]
      }
    },
    // 组内添加
    addRange(it, index) {
      console.log(index)
      const row = {
        fieldId: '', // name
        fieldName: '',
        conditions: '', // 条件
        conditionsList: this.conditionsList,
        detailsList: this.dealdetailsList,
        type: '',
        fieldValue: '',
        // 字典list
        chooseList: []
      }
      this.form.searchDefaultGroup[index].searchDefaultConditionsList.push(row)
    },
    // 获取type
    detailsChange(index, ind, val) {
      const item = this.dealdetailsList.filter(item => item.name === val)
      // 获取字典
      if (item[0].format != null || item[0].format !== '') {
        this.getDicts(item[0].format).then(format => {
          if (format.data && format.data.length > 0) {
            this.form.searchDefaultGroup[index].searchDefaultConditionsList[ind].chooseList = format.data
          }
        })
      }
      this.form.searchDefaultGroup[index].searchDefaultConditionsList[ind].fieldName = item[0].name
      this.form.searchDefaultGroup[index].searchDefaultConditionsList[ind].type = item[0].type
      this.form.searchDefaultGroup[index].searchDefaultConditionsList[ind].fieldValue = ''
    },
    // 删除组内条件
    delRange(it, index) {
      if (it.searchDefaultConditionsList.length > 1) {
        it.searchDefaultConditionsList.splice(index, 1)
      }
    },
    // 删除筛选条件
    delFiltrate(index) {
        this.form.searchDefaultGroup.splice(index, 1)
    },
    // 初始化数据
    init(data) {
        if (data != null && data.id != null && data.id !== '') {
            this.loading = true
            getSearchDefaultView(data.id).then(response => {
                this.form = response.data
                this.loading = false
            })
        } else {
            this.resizeForm()
        }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        color: '',
        name: '',
        sqlBaseId: '',
        sort: '',
        searchDefaultShowList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
        this.$parent.$parent.formOpen = false
        this.resizeForm()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.loading = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          saveSearchDefaultView(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.loading = false
              this.$parent.$parent.formOpen = false
              this.$parent.$parent.getList()
            } else {
              this.loading = false
              this.msgError(response.msg)
            }
          }).catch(() => { })
        }
      })
    }

  }

}
</script>
<style scoped>
.inlineForm{
  width:150px;
  display: inline-block;
  margin-right: 15px;
}
.inlineUser{
  width:150px;display: inline-block;vertical-align: bottom;margin-right: 15px;
}
.smallC{
  padding: 3px;
}
.colorChoose li.active {
  position: relative;
}

.colorChoose li.active:after {
  position: absolute;
  content: '';
  display: block;
  top: 15px;
  right: 18px;
  width: 6px;
  height: 11px;
  border-style: solid;
  border-color: white;
  border-width: 0 2px 2px 0;
  -webkit-transform: rotateZ(45deg);
  transform: rotateZ(45deg);
}

.colorChoose li {
  float: left;
  cursor: pointer;

}
.rangeItem>div{
  margin-bottom: 10px;
}
.rangeItem>div:last-child{
  margin-bottom: 0px;
}

.colorChoose li span {
  height: 24px;
  width: 24px;
  display: block;
  margin: 10px;
}

.el-form .el-form-item .el-form-item__label {
  display: block;
  width: 100%;
  text-align: left;
  font-size: 12px;
  line-height: 24px;
  color: #525975;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}
</style>
